/**
 * 当系统代码运行到这里的时候，必定会从Applaction dump下配置信息。
 */
$$.cfg = (function (){
    var 
         url     = Request.ServerVariables("HTTP_REFERER")() || Request.ServerVariables("PATH_INFO")()
        ,arr	 = url.split('/')
        ,cfgObj  = Application.StaticObjects("dict").Item("initConfig") || (function(){throw '未准备好你的配置文件';})()
        ,cilObjs;
    for(var i in cfgObj){
    	cfgObj  = cfgObj[i];
    	cilObjs = cfgObj['edk_children'];
    	break;
    }
    if(cfgObj && cilObjs && arr.length > 2){
    	if(Request('forceID')()){
    		return cilObjs[Request('forceID')()];
    	}else{
    		
	        for(var i = 0; i < arr.length; i++){
	        	if(arr[i]){
		            if(cilObjs[arr[i]]){
		                return cilObjs[arr[i]]; // 找到子网站，立刻返回
		            }
	        	}
	        }
	        return cfgObj; // 不是子网站，却是二级的目录，没问题，也返回initConfig
    	}
    }else{
        return cfgObj; // 就是根目录，所以返回initConfig
    }
})();

// test fastXML('//page//style_1//table')
$$.cfg.Tags = function(XPath){
    return Application.StaticObjects("dict").Item("tplCache").selectSingleNode(XPath).xml;
}

// 打印头部	
$$.cfg.headTags = function(cfg, load_extjs){
	var 
		 cfg = cfg || $$.cfg
		,cfg = $$.apply({
			'static'    : (cfg.edk_isDebugging ? "http://localhost:8080" : "http://static.ajaxjs.com")
			,load_extjs : !!load_extjs
			,extCDN		: (cfg.edk_isDebugging ? "http://localhost:8080" : "http://extjs.cachefly.net")
		}, $$.cfg) 
		,tpl = $$.cfg.Tags('//page/head').replace('<head>', '').replace('</head>', '')
		,tpl = new $$.Template(tpl, cfg)
		,tpl = tpl.html;
	return tpl;
}

page = {
	/**
	 * @return {String}
	 */
	nav: function(){
        var 
             root = $$.cfg.edk_root 
            ,lis  = $$.cfg.edk_siteTree
            ,link = '<li><a href="{0}" title="{1}">{1}</a></li>' 
            ,arr  = [];

        for(var i = 0; i < lis.length; i++){
            arr.push(link.format(root + lis[i].id, lis[i].text));
        }
        return "<ul>" + link.format(root, "首页") + arr.join('') +"</ul>";
	}
	

	/**
	 * 
	 * @param {Number} level
	 * @param {Function} fn
	 * @return {Object}
	 */
	,getMenuByLevel : function(level, fn) {
		level++;
		var arr = Request.ServerVariables('url')().split('/');
		if($$.cfg.edk_root == "/"){
            arr[0] = '_root_';
		}else{
            arr.shift();
		}
		//arr[0] = page.cfg.edk_root == "/" ? : ;

		var output = {}, prefix = '';
		var _level = 0;

		(function(obj) {
			_level++;
			var currentID = arr.shift();
			prefix += currentID + '/';
			this[prefix] = obj;

			// 到达指定的层数，直接返回对象
			if (level && (level == _level)) {
				output = obj;
				return;
			}
			if (obj && obj.children) {
				var child;
				for (var i = 0, j = obj.children.length; i < j; i++) {
					child = obj.children[i];
					if (child && arr[0] == child.id && !child.hidden && !child.forAdmin) {

						arguments.callee.call(obj, child);
					}
				}
			}
		}).call(output, {
            id : '_root_',
            children : $$.cfg.edk_siteTree
        });

		return output;
	}
	/**
	 * 
	 * @param {Number} level
	 * @param {Function} fn
	 * @return {Object}
	 */
	,getMenuByLevel : function(level, fn) {
		level++;
		var arr = Request.ServerVariables('url')().split('/');
		if($$.cfg.edk_root == "/"){
            arr[0] = '_root_';
		}else{
            arr.shift();
		}
		//arr[0] = page.cfg.edk_root == "/" ? : ;

		var output = {}, prefix = '';
		var _level = 0;

		(function(obj) {
			_level++;
			var currentID = arr.shift();
			prefix += currentID + '/';
			this[prefix] = obj;

			// 到达指定的层数，直接返回对象
			if (level && (level == _level)) {
				output = obj;
				return;
			}
			var children = obj.children;
			if (children) {
				for (var i = 0, j = obj.children.length; i < j; i++) {
					arguments.callee.call(obj, obj.children[i]);
				}
			}
		}).call(output, {
            id : '_root_',
            children : $$.cfg.edk_siteTree
        });

		return output;
	}
	,getSecondMenu : function() {
		var 
			 parent = this.getMenuByLevel(1)
			,second = this.getMenuByLevel(2)// 得到二级菜单
			,arr 	= []
			,arrS 	= parent.children;

		var  node
			,url	// 当前id
			,text;	// 当前id
		function node2html(node){
			var
				 text	= node.text
				// 给url添加参数
				,url	= node.isURL_Link() ? node.getURL_Link() : url
				,isBold = second.id == node.id ? 'style="font-weight:bold;"' : ''
				,li		= '<li {2}><a href="' + $$.cfg.app_root + parent.id + '/{0}">{1}</a></li>'
				,li		= li.format(url, text, isBold);
			
			this.push(li);
		}
		if (arrS && arrS.length) {
			for (var i = 0, j = arrS.length; i < j; i++) {
				node = new $$.node(arrS[i]);
				
				if (!node.isHidden && !node.isforAdmin) {
					if(node.isDB_Link === true){
						$$.each(node.getDB_Link(), node2html, arr);
					}else{
						node2html.call(arr, node);
					}
				}
			}
			return {
				 id 		: parent.id
				,text 		: parent.text
				,children 	: "<ul>" + arr.join('') + "</ul>"
				,current 	: second
			};
		}
	}
	,path : function() {
		var arr = Request.ServerVariables('url')().split('/');
		arr[0] = '_root_';
		var output = {}, prefix = '';

		(function(obj) {
			var currentID = arr.shift();
			prefix += currentID + '/';
			this[prefix] = obj;

			if (obj && obj.children) {
				var child;
				for (var i = 0; i < obj.children.length; i++) {
					child = obj.children[i];
					if (child && arr[0] == child.id && !child.hidden
							&& !child.forAdmin) {
						arguments.callee.call(obj, child);
					}
				}
			}
		}).call(output, {
					id : '_root_',
					children : Application.StaticObjects("dict").Item('WebSiteMap')
				});
		return '<a href="">首页</a> »  <a href="">首页</a>  <a href="">首页</a>';
	}
};

/**
 * @class $$.node
 */
$$.node = function(cfg){
	$$.apply(this, cfg);
	this.url = this.id;
}
$$.node.prototype = {
	 text			: 'Edk节点'
	,url 			: '/'
	,iconCls		: null
	,isforAdmin		: false
	,isHidden		: false
	,isURL_Link		: function(){
		return !!this.baseParam;
	}
	,getURL_Link	: function(){
		return this.baseParam.format($$.cfg.app_root);
	}
	,baseParam		: null
	,isDB_Link		: false
	,getDB_Link		: function(){
		if(this.isDB_Link){
			// query db
			if(!this.DB_link){
				var 
					 sql 		 = $$.newInstance($$.sql)
					,sql		 = sql.list(this.sql)
					,arr		 = []
					,queryString = this.queryString;
				
				$$.each(sql.data, function(data){
					$$.apply(data, {
						 baseParam : queryString + data.ID
						,text	   : data.title + '一览'
					});
					this.push(new $$.node(data));
				}, arr);
				
				this.DB_link = arr;
			}
			
			return this.DB_link;
		}else{
			throw '这不是一个DB_Link';
		}
	}
	// 转换为Ext的数据结构
	,getExt_TreeNode: function(){
		
	}
};

/**
 * @class websiteMap
 * 构建网站地图的类。 
 */
websiteMap = function(){
	this.nodes = [];
	this.rootNode = {
		id : '',
		text : '首页',
		children : $$.cfg['edk_siteTree']
	};
	
	this.addNode(this.rootNode);
}
/**
 * 递归此函数将树的所有节点输出。
 * @param {Object} node
 * @param {String} parentObj_Path
 * @param {Object} _traceObj
 */
websiteMap.prototype.addNode = function (node, parentObj_Path, _traceObj) {
	node.width	= _traceObj ? _traceObj.num : 0;
	node.path	= parentObj_Path? (parentObj_Path + '/' + node.id) : node.id;;
	if (!node.hidden && !node.forAdmin) {
		this.nodes.push({
			 text	: node.text
			,id		: node.id
			,path	: node.path
			,width	: node.width
		});
	}
	if (node.children && node.children.length > 0) {
		if (_traceObj) {
			_traceObj.num += 5; // 缩进的宽度
		}
		for (var i = 0; i < node.children.length; i++) {
			arguments.callee.call(this, node.children[i], node.path, _traceObj || new websiteMap.traceObj);
		}
	}
}
websiteMap.prototype.link	= '<div>{0}<a href="{1}">{2}</a><br /><br /></div>';
/**
 * 将list中每一个node转化为HTML渲染输出。
 * @return {String}
 */
websiteMap.prototype.render = function(){
	var o = [];
	
	for (var i = 0; i < this.nodes.length; i++) {
		var _s = new Array(this.nodes[i].width + 5);
		o.push(
			 this.link.format(_s.join('&nbsp;')
			,$$.cfg.edk_root + this.nodes[i].path
			,this.nodes[i].text)
		);
	}
	return o.join('');
}
/**
 * 用于缩进宽度的内部类。
 */
websiteMap.traceObj = function () {
	this.num = 0;
}